#include <rtthread.h>
#include "board.h"

static char str[] = "Hello RT-Thread!\r\n";
struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;  /* 初始化配置参数 */

static rt_device_t serial;                /* 串口设备句柄 */

static struct rt_semaphore rx_sem;    /* 用于接收消息的信号量 */

/* 接收数据回调函数 */
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
    /* 串口接收到数据后产生中断，调用此回调函数，然后发送接收信号量 */
    rt_sem_release(&rx_sem);

    return RT_EOK;
}

/* 接收数据的线程 */
static void serial_thread_entry(void *parameter)
{
    char ch;

    while (1)
    {
        /* 从串口读取一个字节的数据，没有读取到则等待接收信号量 */
        while (rt_device_read(serial, -1, &ch, 1) != 1)
        {
            /* 阻塞等待接收信号量，等到信号量后再次读取数据 */
            rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
        }
        /* 读取到的数据通过串口错位输出 */
        ch = ch + 1;
        rt_device_write(serial, 0, &ch, 1);
        if (ch == '\n') {
            break;
        }
    }
    rt_kprintf("%s: exit!\n", __func__);
}

int uart_test(int argc, char* argv[])
{
    const char* name = argc > 1 ? argv[1] : "uart2";

    /* step1：查找串口设备 */
    serial = rt_device_find(name);
    if (serial == RT_NULL) {
        rt_kprintf("find %s failed!\n", name);
        return -1;
    }

    /* step2：修改串口配置参数 */
    config.baud_rate = BAUD_RATE_115200;        //修改波特率为 9600
    config.data_bits = DATA_BITS_8;           //数据位 8
    config.stop_bits = STOP_BITS_1;           //停止位 1
    config.bufsz     = 128;                   //修改缓冲区 buff size 为 128
    config.parity    = PARITY_NONE;           //无奇偶校验位

    /* step3：控制串口设备。通过控制接口传入命令控制字，与控制参数 */
    RT_ASSERT(rt_device_control(serial, RT_DEVICE_CTRL_CONFIG, &config) == RT_EOK);

    /* step4：打开串口设备。以中断接收及轮询发送模式打开串口设备 */
    RT_ASSERT(rt_device_open(serial, RT_DEVICE_FLAG_STREAM | RT_DEVICE_FLAG_INT_RX) == RT_EOK);

    /* 初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);

    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial, uart_input);

    rt_thread_t thread = rt_thread_create("uart", serial_thread_entry, RT_NULL, 1024, 20, 10);
    RT_ASSERT(thread);

    RT_ASSERT(rt_thread_startup(thread) == RT_EOK);
    rt_device_write(serial, 0, str, (sizeof(str) - 1));
    return 0;
}
MSH_CMD_EXPORT(uart_test, UART test);

int uart_pin_test(int argc, char* argv[])
{
    rt_base_t pd5 = GET_PIN(D, 5);
    rt_base_t pd6 = GET_PIN(D, 6);

    rt_pin_mode(pd5, PIN_MODE_OUTPUT);
    rt_pin_mode(pd6, PIN_MODE_OUTPUT);

    int v5 = PIN_HIGH;
    int v6 = PIN_LOW;
    for (int i = 0; i < 10; i++) {
        rt_kprintf("[%d] pd5=%d, pd6=%d ...\n", i, v5, v6);
        rt_pin_write(pd5, v5);
        rt_pin_write(pd6, v6);
        rt_thread_mdelay(3000);
        v5 = !v5;
        v6 = !v6;
    }
    rt_kprintf("done!\n");
    return 0;
}
MSH_CMD_EXPORT(uart_pin_test, UART pin test);
